import wx
import os
import sys
import sqlite3
import gui_ui
import pyautogui  # pip install opencv-python pyautogui ntplib progressbar oss2 wxpython pillow
import pathlib
from inc import *
from ossinc import *
import threading
import time


root=pathlib.Path(os.path.dirname(os.path.realpath(sys.argv[0])))
db=sqlite3.connect(str(root/"yj.db"),check_same_thread=False)
cur = db.cursor()
dx=['零','一','二','三','四','五','六','七','八','九','十']
conf=readconfig()
mouse_x=conf.getint("autoPrint",'mouse_x')
mouse_y=conf.getint("autoPrint",'mouse_y')


sql="select kc from main group by kc"
r=cur.execute(sql)
kc=[]
for i in r.fetchall():
    kc.append(getAlias(i[0]))
print(kc)

def pr(obj):
    
    if(obj.m_choice1.GetSelection()>0):
        where1="and nj = \'{0}\'".format(str(obj.m_choice1.GetSelection()+6))
    else:
        where1 = ""
    if(obj.printTpye=="bj"):
        no_=getClassNo(obj.m_choice2.GetStringSelection())
    else:
        no_=getExamNo(obj.m_choice2.GetStringSelection())
    sql="select count(*) from main where {type}='{0}' {1}".format(no_,where1,type=obj.printTpye)
    r=cur.execute(sql)
    r=r.fetchall()
    x, y = pyautogui.position()
    c_ = 2 if p.m_checkBox1.IsChecked() else 1
    pyautogui.click(mouse_x, mouse_y)
    time.sleep(0.3)
    pyautogui.hotkey('ctrlleft','p') # 打印 
    pyautogui.typewrite(str(r[0][0]))   #打印数量
    pyautogui.press("tab")  
    pyautogui.typewrite(f"{c_:d}")   #拷贝
    pyautogui.press("tab")  
    pyautogui.typewrite("1")   #起始记录
    pyautogui.press("enter")   #打印
    pyautogui.moveTo(x,y-35)
    pyautogui.click()
    pyautogui.moveTo(x,y)
    if(r[0][0] %2 ==1 and c_==1):
        co=localconfig.getint('local', 'count')+r[0][0]+1
    else:
        co=localconfig.getint('local', 'count')+(r[0][0]*c_)
    localconfig.set('local', 'count', str(co)) 
    localconfig.write(open(str(root/"configLocal.ini"), "w"))
    p.m_staticText4.Label= str(co)


class f (gui_ui.MyFrame1):
    def __init__(self, parent):
        gui_ui.MyFrame1.__init__(self, parent)
        try:
            self.SetSize(conf.getint("winSize","w"), conf.getint("winSize","h"))
        except:
            print("配置异常")
        
    def dataUP(self,event):
        dlg = wx.MessageDialog(None, u"是否上传文件", u"是否上传文件", wx.YES_NO | wx.ICON_QUESTION)
        if dlg.ShowModal() == wx.ID_YES:
            try:
                multipartUpload(str(root/"yj.db"),"yj/yj.db")
                multipartUpload(str(root/"config.ini"),"yj/config.ini")
                multipartUpload(str(root/"学生信息.xls"),"yj/学生信息.xls")
                multipartUpload(str(root/"班级座位.xlsx"),"yj/班级座位.xlsx")
            except :
                ShowMessage("文件上传失败")
            else:
                ShowMessage(u"文件上传成功")
        event.Skip()
        return False
    def clearCount(self,event):
        localconfig.set('local', 'count', str(0)) 
        localconfig.write(open(str(root/"configLocal.ini"), "w"))
        p.m_staticText4.Label= str(0)
    def dataDown(self,event):
        global db
        global cur
        global conf
        db.close()
        try:
            getfile(root,'config.ini',"yj/config.ini")
            conf=readconfig()
            getfile(root,'yj.db',"yj/yj.db")
            getfile(root,'学生信息.xls',"yj/学生信息.xls")
            getfile(root,'班级座位.xlsx',"yj/班级座位.xlsx")
        except :
            ShowMessage("文件下载失败")
        else:
            ShowMessage("文件下载成功")
            db=sqlite3.connect(str(root/"yj.db"))
            cur = db.cursor()
        event.Skip()
        return False
    def onkc( self, event ):
        ShowMessage("按考场顺序打印")
        p.m_staticText3.Label= u"当前考场"
        p.m_button1.Label= u"打印当前考场"
        p.m_button2.Label= u"打印下一考场"
        p.m_button3.Label= u"刷新当前考场"
        p.printTpye="kc"
        p.choiceGrade(None)
        event.Skip()
    def onbj( self, event ):
        ShowMessage("按班级顺序打印")
        p.m_staticText3.Label= u"当前班级"
        p.m_button1.Label= u"打印当前班级"
        p.m_button2.Label= u"打印下一班级"
        p.m_button3.Label= u"刷新当前班级"
        p.printTpye="bj"
        p.choiceGrade(None)
        event.Skip()
    def onClose(self, event):
        conf.set("winSize","w",str(self.GetSize()[0]))
        conf.set("winSize","h",str(self.GetSize()[1]))
        conf.write(open(str(root/"config.ini"), "w"))
        event.Skip()
    def s(self, event):
        print(self.GetSize())
        return super().s(event)
    def manualPos(self, event):
        global mouse_x
        global mouse_y
        for i in range(10):
            x, y = pyautogui.position()
            print(x, y)
            time.sleep(0.5)

        mouse_x=x
        mouse_y=y
        pyautogui.moveTo(mouse_x,mouse_y)
        conf.set("autoPrint","mouse_x",str(mouse_x))
        conf.set("autoPrint","mouse_y",str(mouse_y))
        conf.write(open(str(root/"config.ini"), "w"))
        ShowMessage(f"{x},{y}")
        event.Skip()

        
class p1(gui_ui.MyPanel1):
    def __init__(self, parent):
        gui_ui.MyPanel1.__init__(self, parent)
        self.printTpye="kc"
        self.m_staticText4.Label= str(localconfig.getint('local', 'count')) #####################################################
        self.m_choice2.SetItems([("         ")])
        my_thread = threading.Thread(target=choiceGradeinit, args=(), name='task')
        my_thread.start()
        #self.choiceGrade(None)

    def choiceGrade(self, event):
        print(self.m_choice1.GetSelection())
        if(self.m_choice1.GetSelection()>0):
            where2="where nj={}".format(self.m_choice1.GetSelection()+6)
        else:
            where2=""
        sql="select {1} from main {0} group by {1}".format(where2,self.printTpye)
        r=cur.execute(sql)
        kc=[]
        for i in r.fetchall():
            kc.append(getExamAlias(i[0])+"")
        self.m_choice2.SetItems(kc)
    def click_double( self, event ):
        print(self.m_checkBox1.IsChecked())
        event.Skip()
    def click1( self, event ):
        if(self.getData(self.m_choice2.GetStringSelection())):
            pr(self)
        event.Skip()
    def click2( self, event ):
        if(self.m_choice2.GetSelection()+1==self.m_choice2.GetCount()):
            ShowMessage("已经是最后一个考场了")
        else:
            self.m_choice2.SetSelection(self.m_choice2.GetSelection()+1)
            if(self.getData(self.m_choice2.GetStringSelection())):
                pr(self)
        event.Skip()
    def click3( self, event ):
        print(self.m_choice2.GetStringSelection())
        if(self.getData(self.m_choice2.GetStringSelection())):
            x, y = pyautogui.position()
            pyautogui.click(mouse_x, mouse_y)
            pyautogui.moveTo(x,y)
        event.Skip()
    def getData(self,kc):
        if(self.m_choice2.GetSelection()==-1):
            self.ShowMessage("请选择考场")
            return False
        print(self.m_choice2.GetSelection())
        print(self.m_choice1.GetSelection())
        if(self.m_choice1.GetSelection()>0):
            where1="and nj = \'{0}\'".format(str(self.m_choice1.GetSelection()+6))
        else:
            where1 = ""
        if(self.printTpye=="bj"):
            kct=getClassNo(kc)
        else:
            kct=getExamNo(kc)
        sql="select kh,name,bj,kc,z,p from main where {type}='{kc}' {wh} order by z,p".format(kc=kct,wh=where1,type=self.printTpye)
        r=cur.execute(sql)

        with open(str(root/"temp.txt"), 'w') as f:
            f.write('考号,考场,班级,年级,姓名,序号\n')
            sql="select nj from main where {type}='{kc}' {wh}  group by nj".format(kc=kct,wh=where1,type=self.printTpye)
            nj=cur.execute(sql)

            for nj_ in nj.fetchall():
                n=1
                sql="select z from main where {type}='{kc}' and nj='{nj_}' {wh}  group by z order by z".format(kc=kct,wh=where1,type=self.printTpye,nj_=nj_[0])
                z=cur.execute(sql)
                for z_ in z.fetchall():
                    if(int(z_[0]) % 4 in (1,2)):
                        sql="select kh,name,bj,kc,z,p from main where {type}='{kc}' and nj='{nj_}' and z='{z_}' {wh} order by p asc".format(kc=kct,wh=where1,type=self.printTpye,nj_=nj_[0],z_=z_[0])
                    else:
                        sql="select kh,name,bj,kc,z,p from main where {type}='{kc}' and nj='{nj_}' and z='{z_}' {wh} order by p desc".format(kc=kct,wh=where1,type=self.printTpye,nj_=nj_[0],z_=z_[0])
                    r=cur.execute(sql)
            
                    for i in r.fetchall():
                        print(n,i)
                        #f.write("{kh},{name},{lj}年级,{bj}班,{kc},{n}".format(kh=i[0],name=i[1],lj=dx[i[2][0]],bj=i[2][2:],kc=i[3]))
                        f.write("{kh},{kc},{bj}班,{lj}年级,{name},{n}\n".format(kh=i[0],name=i[1],lj=dx[int(i[2][0])],bj=getAlias(i[2][2:]),kc=getExamAlias(i[3]),n=n))
                        n=n+1
            f.close()
        return True
    # 手动定位
    # def findLocation(self,event):
    #     global mouse_x
    #     global mouse_y
    #     n=0
    #     while True :
    #         time.sleep(0.1)
    #         x, y = pyautogui.position()
    #         self.m_staticText31.SetLabel(f"{x},{y}  ")
    #         if(x==mouse_x and y==mouse_y):
    #             n=n+1
    #         else:        
    #             mouse_x=x
    #             mouse_y=y
    #             n=0
    #         if(n>=5):
    #             conf.set("autoPrint","mouse_x",str(mouse_x))
    #             conf.set("autoPrint","mouse_y",str(mouse_y))
    #             conf.write(open(str(root/"config.ini"), "w"))
    #             self.m_staticText31.SetLabel("")
    #             ShowMessage(f"定位到{x},{y}")
    #             break
    #     event.Skip()
    def findLocation( self, event ):
        global mouse_x
        global mouse_y
        print(str(root/"01.png.data"))
        r_location = pyautogui.locateOnScreen(str(root/"png.data"), confidence=0.8, grayscale=True)
        if(r_location!=None):
            mouse_x=r_location[0]+8
            mouse_y=r_location[1]+10
            pyautogui.moveTo(mouse_x,mouse_y)
            conf.set("autoPrint","mouse_x",str(mouse_x))
            conf.set("autoPrint","mouse_y",str(mouse_y))
            conf.write(open(str(root/"config.ini"), "w"))
        else:
            ShowMessage("没有找到刷新按钮")
        event.Skip()

def ShowMessage(msg):
    return wx.MessageBox(msg, " " ,wx.OK | wx.ICON_INFORMATION) 

def choiceGradeinit():
    time.sleep(0.1)
    p.choiceGrade(None)


app = wx.App()
w = f(None)
p = p1(w)

w.Show()
app.MainLoop()
